#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""  
@Project : PythonProject
@File : utils.py.py
@Author : donc
@Time : 2025/5/31 2:17
@脚本说明 :

"""
# utils.py
import requests
import base64
import streamlit as st
import os
import requests
from PIL import Image
import io

def load_lottieurl(url: str):
    try:
        r = requests.get(url)
        if r.status_code == 200:
            return r.json()
        else:
            print(f"Error loading Lottie URL: {r.status_code}")
            return None
    except requests.exceptions.RequestException as e:
        print(f"Request exception: {e}")
        return None


def set_background(image_path=None, opacity=0.2):
    """设置应用背景"""
    if not image_path:
        # 默认背景
        st.markdown(
            """
            <style>
            .stApp {
                background: linear-gradient(135deg, #1a2a6c, #b21f1f, #fdbb2d);
                background-size: 400% 400%;
                animation: gradient 15s ease infinite;
            }
            @keyframes gradient {
                0% { background-position: 0% 50%; }
                50% { background-position: 100% 50%; }
                100% { background-position: 0% 50%; }
            }
            </style>
            """,
            unsafe_allow_html=True
        )
        return

    # 从路径读取图片并转换为Base64
    if os.path.exists(image_path):
        with open(image_path, "rb") as f:
            img_bytes = f.read()
    elif image_path.startswith("http"):
        response = requests.get(image_path)
        img_bytes = response.content
    else:
        return

    encoded_image = base64.b64encode(img_bytes).decode()

    # 应用背景图
    st.markdown(
        f"""
        <style>
        .stApp {{
            background: linear-gradient(rgba(255, 255, 255, {1 - opacity}), 
                        url(data:image/png;base64,{encoded_image});
            background-size: cover;
            background-position: center;
            background-attachment: fixed;
            background-repeat: no-repeat;
        }}
        </style>
        """,
        unsafe_allow_html=True
    )